package br.ucb.musicbay.managedBean;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.util.Locale;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;

import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

public class FileUploadController implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 6850111269864482214L;
	private UploadedFile file;
	private byte[] by;
	
	public FileUploadController() {
		setBy(null);
	}

	public byte[] getBy() {
		return by;
	}

	public void setBy(byte[] by) {
		this.by = by;
	}

	public UploadedFile getFile() {
		return file;
	}

	public void setFile(UploadedFile file) {
		this.file = file;
	}

	public void handleFileUpload(FileUploadEvent fileEvent) {
		BufferedImage imagem;
		FacesContext context = FacesContext.getCurrentInstance();
		FacesMessage msg;
		try {
			imagem = ImageIO.read(fileEvent.getFile().getInputstream());
			ByteArrayOutputStream bytesImg = new ByteArrayOutputStream();
			ImageIO.write((BufferedImage) imagem, "jpg", bytesImg);
			bytesImg.flush();
			byte[] byteArray = bytesImg.toByteArray();
			bytesImg.close();
			setBy(byteArray);
			if(context.getViewRoot().getLocale().equals(new Locale("en")))
				msg = new FacesMessage("Success! Picture was uploaded.");
			else
				msg = new FacesMessage("Sucesso! Foto foi carregado");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		} catch (Exception e) {
			if(context.getViewRoot().getLocale().equals(new Locale("en")))
				msg = new FacesMessage("Error! Picture was not loaded");				
			else
				msg = new FacesMessage("Erro! Foto nao foi carregado");
			FacesContext.getCurrentInstance().addMessage(null, msg);
			e.printStackTrace();
		}
	}
}
